import { useEffect, useRef, useState } from 'react';
import { SPACE } from '@/constants/themeConstant.js';
import { Button, Flex, Input, Form, Popconfirm } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import FormModal from '@/components/FormModal/index.jsx';
import ModalUtil from '@/utils/modal.js';

/**
 * 对象编辑器
 *
 * @param props {object} 属性
 * @param props.initialObject {object} 初始对象
 * @param props.onObjectChange {function} 对象变化时的回调函数
 * @param props.keyTitle {string} 键的标题
 * @param props.valueTitle {string} 值的标题
 */
export default function ObjectEditor(props) {
  const { initialObject = {}, onObjectChange } = props;
  const [object, setObject] = useState({});
  const keyTitle = props?.keyTitle ?? '键';
  const valueTitle = props?.valueTitle ?? '值';
  const modalRef = useRef();

  useEffect(() => {
    if (typeof initialObject === 'object') {
      setObject(initialObject);
    }
  }, [initialObject]);

  const updateObject = (key, value) => {
    const newObject = { ...object, [key]: value };
    setObject(newObject);
    onObjectChange?.(newObject);
  };

  const removeKey = (key) => {
    const newObject = { ...object };
    delete newObject[key];
    setObject(newObject);
    onObjectChange?.(newObject);
  };

  const addKey = (values) => {
    if (Object.prototype.hasOwnProperty.call(object, values.key)) {
      ModalUtil.error(`${keyTitle}已经存在`);
      return;
    }
    const newObject = { ...object, [values.key]: values?.value ?? '' };
    setObject(newObject);
    onObjectChange?.(newObject);
    modalRef.current?.close();
  };

  return (
    <>
      <Flex vertical gap={SPACE}>
        {Object.entries(object).map(([key, value]) => {
          return (
            <Flex key={key} gap={SPACE}>
              <Input disabled value={key} />
              <Input
                value={value}
                onChange={(e) => updateObject(key, e.target.value)}
                placeholder={`请输入${valueTitle}`}
              />
              <Popconfirm
                title="提示"
                description="确定删除吗？"
                onConfirm={() => removeKey(key)}
                okText="确定"
                cancelText="取消"
              >
                <Button danger>
                  <DeleteOutlined />
                </Button>
              </Popconfirm>
            </Flex>
          );
        })}
        <FormModal
          ref={modalRef}
          layout="horizontal"
          width={500}
          title={`添加${keyTitle}和${valueTitle}`}
          onFinish={addKey}
          trigger={
            <Button type="primary">
              添加{keyTitle}和{valueTitle}
            </Button>
          }
          formItems={
            <Flex gap={SPACE}>
              <Form.Item
                label={keyTitle}
                name="key"
                rules={[{ required: true, message: `请输入${keyTitle}` }]}
              >
                <Input placeholder={`请输入${keyTitle}`} />
              </Form.Item>
              <Form.Item label={valueTitle} name="value">
                <Input placeholder={`请输入${valueTitle}`} />
              </Form.Item>
            </Flex>
          }
        />
      </Flex>
    </>
  );
}
